import { Model } from 'dva';
import { message } from 'antd';
import userLogin from '@/service/user/login';

export type UserModelState = {
  id: string;
  token: string;
  username: string;
  avatar: string;
}

const userModel: Model = {
  namespace: 'user',
  state: {},
  effects: {
    * login({ payload }, { put, call }) {
      try {
        const user = yield call(userLogin, payload);
        yield put({ type: 'saveState', payload: user });
      } catch (e) {
        message.error(e.message || '登录失败');
      }
    },
    * logOut(action, { put }) {
      yield put({ type: 'resetState' });
      message.success('登出成功');
    },
  },
  reducers: {
    saveState(state: UserModelState, { payload }: any) {
      return { ...state, ...payload };
    },
    resetState() {
      return {};
    },
  },
};

export default userModel;
